import { defineStore } from 'pinia'

export const useActivityStore = defineStore('activity', {
  state: () => ({
    favorites: [], // { id, title, image, date, venue, ts }
    recent: [] // { id, title, image, date, venue, ts }
  }),
  actions: {
    initActivity() {
      try {
        const fav = localStorage.getItem('favorites')
        const rec = localStorage.getItem('recent')
        this.favorites = fav ? JSON.parse(fav) : []
        this.recent = rec ? JSON.parse(rec) : []
      } catch {
        this.favorites = []
        this.recent = []
      }
    },
    persist() {
      localStorage.setItem('favorites', JSON.stringify(this.favorites))
      localStorage.setItem('recent', JSON.stringify(this.recent))
    },
    isFavorite(id) {
      return this.favorites.some(f => f.id === id)
    },
    toggleFavorite(item) {
      const idx = this.favorites.findIndex(f => f.id === item.id)
      if (idx >= 0) {
        this.favorites.splice(idx, 1)
      } else {
        this.favorites.unshift({ ...item, ts: Date.now() })
      }
      this.persist()
    },
    removeFavorite(id) {
      this.favorites = this.favorites.filter(f => f.id !== id)
      this.persist()
    },
    addRecent(item) {
      // 去重并放在最前
      this.recent = this.recent.filter(r => r.id !== item.id)
      this.recent.unshift({ ...item, ts: Date.now() })
      // 限制长度
      if (this.recent.length > 20) this.recent = this.recent.slice(0, 20)
      this.persist()
    },
    clearRecent() {
      this.recent = []
      this.persist()
    }
  }
})